package com.powergisol.gis.controller;

import com.alibaba.fastjson.JSONObject;
import com.powergisol.gis.dao.UserDao;
import com.powergisol.gis.model.Result;
import com.powergisol.gis.model.UserModel;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.nio.charset.Charset;


/**
 * Description:获取token
 */
@RestController
public class AuthController {

    @Value("${system.service.url}")
    private String url;

    @Value("${system.service.key}")
    private String key;

    @Value("${system.service.secret}")
    private String secret;

    @Resource
    private UserDao userDao;

    @GetMapping("/getToken")
    public Result getToken(String userName,String password){
        Result r = new Result();
        UserModel userModel = this.userDao.findByUsername(userName);
        if(null == userModel){
            return r.failure(-1,"用户不存在");
        }
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        String auth = key + ":" + secret;
        byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("US-ASCII")));
        headers.set("Authorization", "Basic " + new String(encodedAuth));

        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.add("scope", "all");
        map.add("username", userName);
        map.add("token", "token");
        if(null != password){
            map.add("password", password);
            map.add("grant_type", "password");
        }else{
            map.add("grant_type", "client_credentials");
        }
        HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(map, headers);

        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> request = restTemplate.postForEntity(url, httpEntity, String.class);
        JSONObject result = JSONObject.parseObject(request.getBody());
        r.setData(result.getString("access_token"));
        return r;
    }

}
